/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.swirrel.listener;

import java.awt.Component;
import java.lang.reflect.Method;
import org.swirrel.util.SwirrelException;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class AbstractSwirrelListener
    implements SwirrelListener {

  private boolean checkSignature(Method method, Class ...classes) {
    for (int i = 0; i < method.getParameterTypes().length; i++) {
      if (!method.getParameterTypes()[i].isAssignableFrom(classes[i])) {
        return false;
      }
    }
    return true;
  }
  protected boolean checkSignature(MethodCall methodCall, Class ...classes) {
    if(methodCall != null) {
      return checkSignature(methodCall.getMethod(), classes);
    } else {
      return true;
    }
  }

  protected void call(MethodCall methodCall, Object ...args) {
    if(methodCall != null) {
      call(methodCall.isThreaded(), methodCall.getMethod(),
           methodCall.getComponent(), args);
    }
  }

  private void call(final boolean threaded, final Method method,
                      final Component comp, final Object ...args) {
    try {
      int length = method.getParameterTypes().length;
      final Object[] callArgs = (length < args.length) ? new Object[length] :
          args;
      if (length < args.length) {
        for (int i = 0; i < length; i++) {
          callArgs[i] = args[i];
        }
      }
      if (threaded) {
        new Thread(new Runnable() {
          public void run() {
            try {
              method.invoke(comp, callArgs);
            }
            catch (RuntimeException ex) {
              throw ex;
            }
            catch (Exception ex) {
              throw new SwirrelException(ex);
            }
          }
        }).start();
      }
      else {
        method.invoke(comp, callArgs);
      }
    }
    catch (RuntimeException ex) {
      throw ex;
    }
    catch (Exception ex) {
      throw new SwirrelException(ex);
    }
  }
}
